var _that;
var app = getApp();
var goodsPerHgt = 80;
var allCarGoods = {};
var scaleAmt = wx.createAnimation({
  duration: 200,
  timingFunction: 'ease-out'
});

function carInit(target) {
  _that = target;
  _that.setData({
    needshow: false,
    carscrollhgt: 0,
    goodslist: [],
    goodsidlist: []
  });

  _that.animation = wx.createAnimation({
    duration: 300,
    timingFunction: 'ease-out',
    // 延迟多长时间开始
    delay: 0,
    transformOrigin: 'left bottom 0',
    success: function (res) {
      console.log(res)
    }
  });
  
  loadCarData();
}

function showDetail() {
  if (_that.data.totalcount <= 0) {
    return;
  }
  var topoffset = _that.data.carscrollhgt;
  _that.setData({
    needshow: true,
    carTopOffset: topoffset
  });
  _that.animation.top(0).step()

  _that.setData({
    car_amt: _that.animation.export()
  });
  
}

function closeDetail() {
  _that.setData({
    needshow: false
  });
}

function update() {

}

function submitOrder(orderinfo) {
  if (_that.data.address == null || _that.data.address == undefined) {
    wx.showToast({
      title: '请先添加收货地址！',
      icon: 'none'
    });
    return;
  }
  if (_that.data.totalcount <= 0) {
    return;
  }
  var curdate = app.currentDate();
  var url = '/yuanmai_we/activity/checkShoppingCart/' + curdate;
  var params = {
    __zaofans: true
  };
  var property = {
    "meals": _that.data.goodslist,
    "cityId": app.globalData.address.CITYID,
    "storeId": _that.data.breadlist[0].storeid
  }
  params.datas = JSON.stringify(property);
  app.loadDataFromServer(url, checkCartCallBack, params, 'post');
}
function checkCartCallBack(res) {
  console.log(res);
  if (res.ok != true) {
    return;
  }
  var stockinfo = res.stockArray;
  for (var i = 0; i < stockinfo.length; i++) {
    stockinfo[i].STOCK.synthesisNotExistStatus = false;
    stockinfo[i].STOCK.synthesisNotStatus = false;
    stockinfo[i].STOCK.synthesisAndStatus = true;
    stockinfo[i].STOCK.synthesisOrStatus = true;
    stockinfo[i].STOCK.synthesisXOrStatus = false;
  }

  wx.navigateTo({
    url: '../neworder/neworder?type=bread&orderinfo=' + encodeURIComponent(JSON.stringify(stockinfo)) + '&address=' + encodeURIComponent(JSON.stringify(_that.data.address)),
  });
}

function startAnimation(){
  scaleAmt.scale(1.5,1.5).step();
  _that.setData({
    scaleAmt: scaleAmt.export()
  });
  var timeid = setTimeout(function(){
    clearTimeout(timeid);
    scaleAmt.scale(1,1).step();
    _that.setData({
      scaleAmt: scaleAmt.export()
    });
  },300);
}

function handleCount(e) {
  startAnimation();

  var options, goodsid;
  if (e.currentTarget) {
    options = parseInt(e.currentTarget.dataset.options);
    goodsid = e.currentTarget.dataset.goodsid;
  }
  else {
    options = e.options;
    goodsid = e.goodsid;
  }
  var goodslist = _that.data.goodslist;
  var goodsidlist = _that.data.goodsidlist;
  // console.log('ddddd');
  var breadlist = _that.data.breadlist;
  var totalcount = parseInt(_that.data.totalcount);
  var totalprice = parseFloat(_that.data.totalprice);
  for (var i = 0; i < breadlist.length; i++) {
    var keyid = breadlist[i].goodsid;
    if (keyid == goodsid) {
      if (options == '1') {
        totalcount += 1;
        totalprice += parseFloat(breadlist[i].price);
        if (goodsidlist.indexOf(keyid) >= 0) {
          goodslist[goodsidlist.indexOf(keyid)].COUNT = parseInt(goodslist[goodsidlist.indexOf(keyid)].COUNT) + 1;
        }
        else {
          goodsidlist.push(keyid);
          var tmpinfo = {
            goodsid: keyid,
            ID: keyid,
            MEALID: breadlist[i].mealid,
            COUNT: '1',
            name: breadlist[i].name,
            price: breadlist[i].price,
            img: breadlist[i].img
          };
          goodslist.push(tmpinfo);
        }
      }
      else {
        if (totalcount > 0 && goodsidlist.indexOf(keyid) >= 0) {
          totalcount -= 1;
          totalprice -= parseFloat(breadlist[i].price);
          goodslist[goodsidlist.indexOf(keyid)].COUNT = parseInt(goodslist[goodsidlist.indexOf(keyid)].COUNT) - 1;
          if (parseInt(goodslist[goodsidlist.indexOf(keyid)].COUNT) <= 0) {
            goodslist.splice(goodsidlist.indexOf(keyid), 1);
            goodsidlist.splice(goodsidlist.indexOf(keyid), 1);
          }
        }
      }
      break;
    }
  }
  totalprice = app.keepTwoDecimalFull(totalprice);
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: goodslist,
    goodsidlist: goodsidlist
  });

  var oldgoods;
  if (allCarGoods[_that.data.breadtype] != null && allCarGoods[_that.data.breadtype] != undefined) {
    oldgoods = allCarGoods[_that.data.breadtype];
  }
  else {
    oldgoods = {};
  }
  oldgoods.totalcount = totalcount;
  oldgoods.totalprice = totalprice;
  oldgoods.goodslist = goodslist;
  oldgoods.goodsidlist = goodsidlist;
  allCarGoods[_that.data.breadtype] = oldgoods;

  adjustHeight();
  if (totalcount == 0) {
    _that.setData({
      needshow: false
    });
  }
}

function resetCar() {
  if (allCarGoods[_that.data.breadtype] != null && allCarGoods[_that.data.breadtype] != undefined) {
    var oldGoods = allCarGoods[_that.data.breadtype];
    console.log(oldGoods);
    _that.setData({
      totalcount: oldGoods.totalcount,
      totalprice: oldGoods.totalprice,
      goodslist: oldGoods.goodslist,
      goodsidlist: oldGoods.goodsidlist
    });
  }
  else {
    _that.setData({
      totalcount: 0,
      totalprice: 0.00,
      goodslist: [],
      goodsidlist: []
    });
  }
  adjustHeight();
}

function checkGoodsCount(goodsid) {
  if (allCarGoods[_that.data.breadtype] == null || allCarGoods[_that.data.breadtype] == undefined) {
    return 0;
  }
  else {
    var oldgoods = allCarGoods[_that.data.breadtype].goodslist;
    var goodsnum = 0;
    for (var i = 0; i < oldgoods.length; i++) {
      if (oldgoods[i].MEALID == goodsid) {
        goodsnum = oldgoods[i].COUNT;
        break;
      }
    }
    return goodsnum;
  }
}

module.exports = {
  init: carInit,
  showCar: showDetail,
  closeCar: closeDetail,
  update: update,
  submitOrder: submitOrder,
  handleCount: handleCount,
  reset: resetCar,
  checkGoodsCount: checkGoodsCount
}

//------以下方法不外调
function loadCarData() {
  var totalcount = 0;
  var totalprice = 0.00;
  _that.setData({
    totalcount: totalcount,
    totalprice: totalprice,
    goodslist: [],
    goodsidlist: []
  });
  adjustHeight();
}

function adjustHeight() {
  var hgt = _that.data.goodslist.length * goodsPerHgt;
  var win_hgt = wx.getSystemInfoSync().windowHeight;
  if (hgt > win_hgt * 0.5) {
    hgt = win_hgt * 0.5;
  }
  hgt += 70;
  _that.setData({
    carscrollhgt: hgt,
    goodsPerHgt: goodsPerHgt
  });
}
